// pages/msglist/msglist.js
var util = require("../../../utils/util.js");
var app = getApp();
var cf = require("../../../config.js");
var changeTime = require("../../../utils/changetime.js");
var cusmallToken = wx.getStorageSync('cusmallToken');
var employee = {};
//获取应用实例
var webim = global.webim;
var webimhandler = global.webimhandler;
var em = require("../../../data_file/emtion")
import messageServ from "./messageServ";
const pageManager = require('../../../lib/js/pageManager');


Page({
  data:{
    staticResPath: cf.config.staticResPath,
    chatPageNo:1,
    chatPageSize:11,
    contactList: [],
    newMessageState: false,
    isShowContactList: true,
    startX: 0, //开始坐标
    startY: 0,
    requestShow:false,
    isNoMessage:false,
    shareMaskActiveList:false
},
   /**
  * 分享活动的列表
  */
 shareMaskActiveList:function(){
  this.setData({
   shareMaskActiveList:true,
   isNoMessage:false
  });
},
  toPoster:function(e){
    let employee = wx.getStorageSync('employee');
    var ctx = this;
    util.addBehaviorTrail(employee.id, 3);
    wx.navigateTo({
      url: '/pages/canvas/index?eId=' + employee.id,
    })
  },
 loadRecentContactList:function () {
      let that = this;
      let openId = wx.getStorageSync('openId');
      employee = wx.getStorageSync("employee");
    
      let {isShowContactList,chatPageNo,chatPageSize,contactList } = this.data;
      let param = {
        openid: openId,
        start: chatPageNo,
        limit: chatPageSize,
        type:2
      }
      messageServ.queryMsgList(param).then((item)=>{
        if(item.msg=="success"){
          var modelList = item.model.list;
          isShowContactList = true;
          if (modelList && modelList.length > 0) {
            modelList.forEach(function (c) {
              changeTime.reset();
              var chatTime = changeTime.getHistoryTimer(c.msgTime) || "刚刚";
              c.date = chatTime;
              c.delName = "删除";
              c.isTouchMove = false;
              c.MsgShow = JSON.parse(c.msgContent);
              var msg = c.MsgShow;
  
              if (msg.msg.options && msg.card_id == employee.id) {
                if (msg.msg.context.indexOf("微信") != -1) {
                  msg.msg.context = c.MsgShow.from_userinfo.nickName + "复制了你的微信"
                }
                if (msg.msg.context.indexOf("你已拨打了") != -1) {
                  msg.msg.context = c.MsgShow.from_userinfo.nickName + "拨打了你的电话"
                }
                if (msg.msg.context.indexOf("名片") != -1) {
                  msg.msg.context = c.MsgShow.from_userinfo.nickName + "保存了你的名片海报"
                }
                if (msg.msg.context.indexOf("授权电话") != -1) {
                  msg.msg.context = c.MsgShow.from_userinfo.nickName + "授权电话成功 " + c.MsgShow.from_userinfo.phone
                }
              }
  
            })
          }
          if(chatPageNo==1&&modelList.length==0){
            isShowContactList = false;
          }
          if(chatPageNo>1){
            contactList = [...contactList,...modelList];
          }else{
            contactList = modelList
          }
            app.getAllUnreadNum('',function (unReadMsgList) {
              if (unReadMsgList && unReadMsgList.length > 0) {
                for (var i = 0; i < unReadMsgList.length; i++) {
                  var unReadMsg = unReadMsgList[i];
                  for (var j = 0; j < modelList.length; j++) {
                    var contact = modelList[j];
                    if (unReadMsg.targetOpenid == contact.memberOpenId) {
                      contact.UnreadMsgCount = unReadMsg.unreadNum;
               
                    } 
                  }
                }
              }
             
              
              that.setData({
                contactList: contactList, isShowContactList
              });
            });
          
        }
        
       
      });
    },
  
    //手指触摸动作开始 记录起点X坐标
    touchstart:function (e) {
      //开始触摸时 重置所有删除
      let { contactList } = this.data;
      if(e.changedTouches&&e.changedTouches.length>0){
        this.setData({
          startX: e.changedTouches[0].clientX,
          startY: e.changedTouches[0].clientY,
          contactList
        })
      }
  
    },
    //滑动事件处理
    touchmove:function (e) {
      var that = this,
        {startX,startY,contactList} = this.data,
        index = e.currentTarget.dataset.index,//当前索引
        touchMoveX = e.changedTouches[0].clientX,//滑动变化坐标
        touchMoveY = e.changedTouches[0].clientY,//滑动变化坐标
        //获取滑动角度
        angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
        contactList.forEach(function (v, i) {
        v.isTouchMove = false
        //滑动超过30度角 return
        if (Math.abs(angle) > 30) return;
        if (i == index) {
          if (touchMoveX > startX){//右滑
            v.isTouchMove = false
            v.delName ='删除'
          }
          else //左滑
            v.isTouchMove = true
        }
      })
      //更新数据
      that.setData({
        contactList
      })
    },
     /**
     * 计算滑动角度
     * @param {Object} start 起点坐标
     * @param {Object} end 终点坐标
     */
    angle:function (start, end) {
      var _X = end.X - start.X,
        _Y = end.Y - start.Y
      //返回角度 /Math.atan()返回数字的反正切值
      return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
    },
    showShareMask:function(){
      this.setData({
        shareMask: true
      })
    },
    hideMask:function(){
      this.setData({
        shareMask: false
      });
    },
     /**
    * 分享活动的列表
    */
   shareMaskActiveList:function(){
    this.setData({
     shareMaskActiveList:true,
     isNoMessage:false
    });
  },
    toPoster:function(e){
      let employee = wx.getStorageSync('employee');
      var ctx = this;
      util.addBehaviorTrail(employee.id, 3);
      wx.navigateTo({
        url: '/pages/canvas/index?eId=' + employee.id,
      })
    },
  
    /**
     * 删除会话
     */
    del:function(e){
      let { contactList,isShowContactList } = this.data;
      let chat_detail = wx.getStorageSync('chat_detail');
      let chatCloseTipsUser = wx.getStorageSync('chatCloseTipsUser');
      let { index,toaccount,fromaccount} = e.currentTarget.dataset
      let that = this;
      if(contactList[index].delName=='确认删除'){
        messageServ.delHistoryMsg({fromAccount:fromaccount,toAccount:toaccount, cusmallToken: wx.getStorageSync('cusmallToken')}).then((item)=>{
          contactList.splice(index,1)
          if(contactList.length==0){isShowContactList=false}
          if(chat_detail[fromaccount]){//删除缓存
            delete chat_detail[fromaccount]
            wx.setStorageSync('chat_detail',chat_detail)
          }
          if(chatCloseTipsUser[fromaccount]){ //删除提示弹出
            delete chatCloseTipsUser[fromaccount]
            wx.setStorageSync('chatCloseTipsUser',chatCloseTipsUser)
          }
          app.getTotalUnreadNum(function () { }, that);
          that.setData({contactList,isShowContactList})
      });
      }else{
        contactList[index].delName='确认删除'
        that.setData({contactList})
      }
     
    },
    /**
     * 跳转聊天室
     */
    onMsgSecTab:function (e) {
      let openid = e.currentTarget.dataset.openid;
      let card_id = e.currentTarget.dataset.cardid;
      let cusmallToken = wx.getStorageSync('cusmallToken');
      const fetchSig = messageServ.getUserSign({
        cusmallToken,
        identifier: openid
      })
      pageManager.putData('fetchSigCusmall',fetchSig);
      wx.navigateTo({  url: '/subPackages/pages/chat/chat?selToID=' + openid + (card_id ? "&card_id=" + card_id : "")});
      
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad (options) {
      webimhandler.setPageCtx(this);
      var that = this;
      that.setData({
        emtions: em.changeEm()
      })
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow (options) {
       if(!this.data.requestShow){
        this.onPreload({isShow:true})
      }
    },
    onHide(){
      this.setData({
        requestShow:false
      });
    },
    /**
     * 预加载数据
     */
    onPreload:function (option){
      let that = this;
      let chatPageNo = 1;
      let isShow = option.isShow;
      that.setData({
        requestShow:isShow,chatPageNo
      });
      webimhandler.setNewMsgListener(function (newmsg) {
        that.loadRecentContactList();
      });
      app.getUserIMSign(()=>{
        that.loadRecentContactList();
        app.getTotalUnreadNum(function () { }, that);
       });
      
    },
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom:function () {
      let { chatPageNo,contactList} = this.data;
      if(contactList.length > 0){
        chatPageNo +=1;
        this.setData({ chatPageNo })
        this.loadRecentContactList();
      }
  
  
    },
  
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage:function(e) {
      let ctx = this;
      let title,path,imageUrl;
      let data = e.target.dataset.item;
      let employee = wx.getStorageSync('employee');
      ctx.setData({shareMaskActiveList:false});
      if(employee){
       title = "你好，我是"+(employee.salesProductName?employee.salesProductName:'置业地产')+'的'+employee.name+',这是我的名片，请惠存。';
       path = "/pages/mycard/card?eId=" + employee.id +"&source=1";
       imageUrl='https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/card/card-img.jpg'
      }
      if(data){
         title = data.title;
         path =data.channel==3? `/subPackages/pages/findHouse/activity/apply/apply?contentId=${data.contentId}&productId=${data.productId}`:`/subPackages/pages/giftManage/giftDetail/giftDetail?giftId=${data.id}`;
         imageUrl=data.titleImgUrl
        }
      //util.addBehaviorTrail(ctx.data.eId, 3);
      //path 添加客户来源
      //path += "&fromOpenId=" + ctx.data.app.globalData.myOpenid + "&fromNickName=" + ctx.data.app.globalData.userInfo.nickName + "&forwardType=page_card";
      let shareObj = {
      title: title,
      path: path,
      imageUrl:imageUrl,
      success: function (res) {
      },
      fail: function (res) {
      }
      };
      return shareObj;
  
    }
  
  
});